package edu.washington.vaccine.ui;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.washington.vaccine.R;
import edu.washington.vaccine.backend.VaccineDB;
import edu.washington.vaccine.backend.VaccineLocalHelper;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

/*
 * 
 * Attempts to cache data from online db onto 
 * the local sql db 
 */

public class CacheActivity extends Activity {
	protected static String URL_START = "http://www.cubist.cs.washington.edu/~bje575/index.php?";
//	private VaccineLocalHelper helper;
//	private SQLiteDatabase db;
//	private TextView tv;
	private ProgressDialog progress;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cache);
		VaccineLocalHelper helper = VaccineLocalHelper.getInstance(this);
		final SQLiteDatabase db = helper.getWritableDatabase();
//		this.tv = (TextView) findViewById(R.id.queryresults);
		final VaccineDB vdb = VaccineDB.getInstance();
		final Toast t1 = Toast.makeText(CacheActivity.this, "Online data successfully cached", Toast.LENGTH_SHORT);
		final Toast t2 = Toast.makeText(CacheActivity.this, "To cache online data, please connect to the internet and enable online mode", Toast.LENGTH_SHORT);

		Button download = (Button) findViewById(R.id.cache_button);
		download.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				progress = ProgressDialog.show(CacheActivity.this, "", "Please wait while caching online data");
				Thread thread = new Thread() {
					public void run() {
						try {
							if (vdb.isOnlineMode() && hasConnection()) {
								downloadPatients(db);
								downloadPatientHistory(db);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						finally {
							progress.cancel();
							if (vdb.isOnlineMode() && hasConnection())
								t1.show();
							else
								t2.show();
						}
					}
				};
				thread.start();
			}
		});
	}

	public boolean hasConnection() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		return activeNetwork != null;
	}

	public static void downloadPatients(SQLiteDatabase db) {
		StringBuilder sb = new StringBuilder();
		String patientString = VaccineDB.httpConn(URL_START + "request=get");
		if (patientString == null) {
			return;
		}

		JSONArray jArr;
		try {
			jArr = new JSONArray(patientString);
			JSONObject json_data = null;
			db.execSQL("DROP TABLE IF EXISTS Patients");
			db.execSQL("create table if not exists Patients (pid text, lname text, fname text, " +
					"dob text, location text, fathername text, mothername text, " +
					"editdate text, conflict text, notes text, primary key(pid, editdate))");
			for (int i = 0; i < jArr.length(); i++) {
				json_data = jArr.getJSONObject(i);
				ContentValues values = new ContentValues();
				String pid = json_data.get("pid").toString();
				String lname = json_data.get("lname").toString();
				String fname = json_data.get("fname").toString();
				String dob = json_data.get("dob").toString();
				String location = json_data.get("location").toString();
				String fathername = json_data.get("fathername").toString();
				String mothername = json_data.get("mothername").toString();
				String editdate = json_data.get("editdate").toString();
				String conflict = json_data.get("conflict").toString();
				String notes = json_data.get("notes").toString();
				
				
				sb.append(pid + "\n");
				values.put("pid", pid);
				values.put("lname", lname);
				values.put("fname", fname);
				values.put("dob", dob);
				values.put("location", location);
				values.put("fathername", fathername);
				values.put("mothername", mothername);
				values.put("editdate", editdate);
				values.put("conflict", conflict);
				values.put("notes", notes);
				db.insert("Patients", null, values);
//				update();
			}
//			tv.setText(sb.toString());
		} catch (JSONException e) {
			return;
		}
	}

	public static void downloadPatientHistory(SQLiteDatabase db) {
		String historyString = VaccineDB.httpConn(URL_START + "request=getPatientHistory");
		if (historyString == null) {
			return;
		}

		JSONArray jArr;
		try {
			jArr = new JSONArray(historyString);
			db.execSQL("DROP TABLE IF EXISTS PatientHistory");
			db.execSQL("create table PatientHistory (pid text, vid text, dategiven text, " +
					"primary key (pid, vid, dategiven))");
			JSONObject json_data = null;
			for (int i = 0; i < jArr.length(); i++) {
				json_data = jArr.getJSONObject(i);
				ContentValues values = new ContentValues();
				String pid = json_data.get("pid").toString();
				String vid = json_data.get("vid").toString();
				String dategiven = json_data.get("dategiven").toString();
				values.put("pid", pid);
				values.put("vid", vid);
				values.put("dategiven", dategiven);
				db.insert("PatientHistory", null, values);
//				update();
			}
		} catch (JSONException e) {
			return;
		}
		return;
	}

	// used for testing purposes
//	public void update() {
//		Cursor cursor = db.rawQuery("SELECT * FROM Patients", new String[]{});
//		startManagingCursor(cursor);
//		// output
//		StringBuilder sb = new StringBuilder();
//		while (cursor.moveToNext()) {
//			String col1 = cursor.getString(0);
//			String col2 = cursor.getString(1);
//			String col3 = cursor.getString(2);
//			sb.append(col1 + ", " + col2 + ", " + col3 + "\n");
//		}
//		tv.setText(sb);
//		cursor.close();
//	}
}
